package com.kede.api.stand.schedu;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.kede.api.stand.domain.Virtual;
import com.kede.api.stand.mapper.VirtualMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.*;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/***
 ** @Author:Pr.li
 ** @Description:
 ** @Date: create in 2023/4/12 15:32
 ***/
@Component
@Slf4j
public class VirtualSchedu implements SchedulingConfigurer {


    static Virtual virtual;

    @Resource
    private VirtualMapper virtualMapper;


//服务器暂时不支持 @Async
//    @Async("virtualThreadPool")
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {


        Runnable tast = new Runnable() {
            @Override
            public void run() {
                LambdaQueryWrapper<Virtual> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Virtual::getName,"randomZHnum");
                virtual = virtualMapper.selectOne(queryWrapper);
                log.info("randomZHnum c触发了，{}",virtual);
                if (Objects.nonNull(virtual)) {
                    LambdaUpdateWrapper<Virtual> updateWrapper = new LambdaUpdateWrapper<>();
                    int i = RandomUtil.randomInt(virtual.getMin(), virtual.getMax()+1);
                    log.info("获取到得随机数为=={}",i);
                    virtualMapper.updateValueByName(virtual.getValue() + i,virtual.getName());
                }
            }
        };

        Trigger trigger = new Trigger(){

            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {

                String cron = "0 0 0/1 * * *";
                if (Objects.nonNull(virtual)){
                    cron = virtual.getCron();
                }
                log.info("configureTasks  cron ================");
                log.info(cron);
                CronTrigger cronTrigger = new CronTrigger(cron);
                return cronTrigger.nextExecutionTime(triggerContext);
            }
        };
        taskRegistrar.addTriggerTask(tast,trigger);
    }
}
